import { createSlice } from '@reduxjs/toolkit';
import http from '@/utils/http';

const counterStore = createSlice({
  name: 'bill',
  // 初始化state
  initialState: {
    billList: []
  },
  // 修改状态的方法 同步方法 支持直接修改
  reducers: {
    setBillList(state, action) {
      state.billList = action.payload;
    },
    addBill(state, action) {
      state.billList.push(action.payload);
    }
  }
});

// 结构出来actionCreate函数
const { setBillList, addBill } = counterStore.actions;
const getBillList = () => {
  return async dispatch => {
    const res = await http.get('/ka');
    dispatch(setBillList(res.data));
  }
}

const addBillList = data => {
  return async dispatch => {
    const res = await http.post('/ka', data);
    dispatch(addBill(res.data));
  }
}

// 获取reducer
const reducer = counterStore.reducer;
// 以按需导出的方式导出actionCretae
export { getBillList, addBillList };
// 以默认导出的方式导出reducer
export default reducer;